package com.candy.learn.datainteraction.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>Title: EventSourceController</p>
 *
 * <p>Description: </p>
 *
 * @date 2018/12/21
 */
@RestController
@RequestMapping("/es")
public class EventSourceController {

    static Integer randomInt = 0;

    @RequestMapping(value = "/testEventSource", produces = "text/event-stream")
    public String testEventSource() {
        //响应报文格式为:
        //data:Hello World
        //event:load
        //id:140312
        //换行符(/r/n)
        StringBuffer result = null;
        // open/load/message/error
        result = new StringBuffer();
        if (randomInt == 0) {
            result = new StringBuffer();
            result.append("event:open");
            result.append("\n");
            result.append("data:" + randomInt++);
            result.append("\n\n");
            return result.toString();
        }

        while (randomInt < 5) {
            result = new StringBuffer();
            result.append("event:load");
            result.append("\n");
            result.append("data:" + randomInt++);
            result.append("\n\n");
            return result.toString();
        }
        result = new StringBuffer();
        result.append("event:load");
        result.append("\n");
        result.append("data:");
        result.append("\n\n");
        return result.toString();
    }
}
